package com.gyz.cfmall.controller;

import com.alibaba.fastjson.TypeReference;
import com.gyz.cfmall.feign.MemberFeignService;
import com.gyz.cfmall.feign.ThirdPartFeignService;
import com.gyz.cfmall.vo.UserLoginVo;
import com.gyz.cfmall.vo.UserRegisterVo;
import com.gyz.common.constant.AuthServerConstant;
import com.gyz.common.exception.BizCodeEnum;
import com.gyz.common.utils.R;
import com.gyz.common.vo.MemberResponseVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author gong_yz
 * @Description
 * @Date 2023/4/6
 */
@Controller
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @Resource
    private ThirdPartFeignService thirdPartFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping(value = "/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {

        // 处理一个手机号码60s内多次获取短信验证码问题
        String s = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (StringUtils.isNotEmpty(s)) {
            //活动存入redis的时间，用当前时间减去存入redis的时间，判断用户手机号是否在60s内发送验证码
            Long currentTime = Long.parseLong(s.split("_")[1]);
            // 单位为毫秒，因此，60秒要转化为毫秒即60000
            if (currentTime - System.currentTimeMillis() < 60000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);

        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo registerVo, BindingResult bindingResult, RedirectAttributes attributes) {
        //参数校验
        if (bindingResult.hasErrors()) {
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(item -> {
                return item.getField();
            }, item -> {
                return item.getDefaultMessage();
            }));
            attributes.addFlashAttribute("errors", errors);

            return "redirect:http://auth.cfmall.com/reg.html";
        }

        //校验验证码
        String code = registerVo.getCode();

        //获取存入Redis里的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
        if (!StringUtils.isEmpty(redisCode)) {
            //截取字符串
            if (code.equals(redisCode.split("_")[0])) {
                //删除验证码;令牌机制
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registerVo.getPhone());
                //验证码通过，真正注册，调用远程服务进行注册
                R register = memberFeignService.register(registerVo);
                if (register.getCode() == 0) {
                    //成功
                    return "redirect:http://auth.cfmall.com/login.html";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.cfmall.com/reg.html";
                }
            } else {
                //效验出错回到注册页面
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.cfmall.com/reg.html";
            }
        } else {
            //效验出错回到注册页面
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.cfmall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(@RequestBody UserLoginVo userLoginVo, RedirectAttributes attributes, HttpSession session) {
        R r = memberFeignService.login(userLoginVo);
        if (r.getCode() == 0) {
            log.info("账号密码登录成功");
            MemberResponseVo data = r.getData("data", new TypeReference<MemberResponseVo>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            return "redirect:http://cfmall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.cfmall.com/login.html";
        }
    }

    /**
     * 判断session是否有loginUser，没有就跳转登录页面，有就跳转首页
     *
     * @param session
     * @return
     */
    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://cfmall.com";
        }
    }
}
